// 提交个人信息表单
function submitForm(type) {
    const form = type === 'accounting' ? document.getElementById('accountingForm') : document.getElementById('developmentForm');
    const formData = new FormData(form);
    const userData = Object.fromEntries(formData.entries());
    userData.type = type;

    // 处理工作经历数据
    const workExperiences = [];
    for (let i = 1; i <= 3; i++) {
        if (formData.get(`workTime${i}`)) {
            workExperiences.push({
                time: formData.get(`workTime${i}`),
                company: formData.get(`company${i}`),
                position: formData.get(`position${i}`),
                reason: formData.get(`reason${i}`)
            });
        }
    }
    userData.workExperiences = workExperiences;

    // 处理教育经历数据
    const educations = [];
    for (let i = 1; i <= 2; i++) {
        if (formData.get(`eduTime${i}`)) {
            educations.push({
                time: formData.get(`eduTime${i}`),
                school: formData.get(`school${i}`),
                certificate: formData.get(`certificate${i}`),
                major: formData.get(`major${i}`)
            });
        }
    }
    userData.educations = educations;

    // 处理布尔值字段
    // 替换原有的formData.get方式为直接检查复选框状态
    userData.overtime = document.querySelector('input[name="overtime"]')?.checked || false;
    userData.businessTrip = document.querySelector('input[name="businessTrip"]')?.checked || false;
    userData.relocate = document.querySelector('input[name="relocate"]')?.checked || false;
    fetch('/api/accounting/save', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(userData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast("提交成功", "success");
            
            // 发送刷新通知到dashboard
            const channel = new BroadcastChannel('dashboard-refresh');
            channel.postMessage('refresh');
            channel.close();
            
            setTimeout(() => {
                if (type === 'development') {
                    window.location.href = 'development-exercises.html';
                } else {
                    // 修改：跳转到习题页面并携带accountingId参数
                    // window.location.href = `development-exercises.html?accountingId=${data.accountingId}`;
                    window.location.href='index.html';
                }
            }, 1500);
        } else {
            showToast('提交失败', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('提交时发生错误', 'error');
    });
}

// 提交练习题答案
// 修改函数定义，添加type参数
// 提交练习题答案
function submitExercises(type) {
    const form = document.getElementById('exerciseForm');
    const formData = new FormData(form);
    const answers = Object.fromEntries(formData.entries());
    // 从URL参数获取accountingId
    const accountingId = new URLSearchParams(window.location.search).get('accountingId');
    answers.accountingId = accountingId;
    
    console.log('提交练习题答案:', answers);
    console.log('accountingId:', accountingId);

    fetch('/api/exercises/submit', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(answers)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 添加：发送刷新通知到dashboard
            showToast("提交成功", "success");
            const channel = new BroadcastChannel('dashboard-refresh');
            channel.postMessage('refresh');
            channel.close();
            
            setTimeout(() => {
                if (type === 'development') {
                    window.location.href = 'development-exercises.html';
                } else {
                    window.location.href = 'index.html';
                }
            }, 1500);
        } else {
            showToast('提交失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('提交时发生错误', 'error');
    });
}

// 表单验证函数
function validateForm(form) {
    let isValid = true;
    const errorMessages = [];
    const requiredFields = form.querySelectorAll('.required');
    const phoneField = form.querySelector('input[name="phone"]');
    const emailField = form.querySelector('input[name="email"]');
    const acceptanceOptions = form.querySelectorAll('.acceptance-option');
    const acceptanceValidation = form.querySelector('input[name="acceptanceValidation"]');
    const idNumberField = form.querySelector('input[name="idNumber"]');

    // 重置所有错误样式
    document.querySelectorAll('.error-message').forEach(el => el.remove());
    document.querySelectorAll('.form-control.error').forEach(el => el.classList.remove('error'));

    // 检查必填字段
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            const label = field.previousElementSibling ? field.previousElementSibling.textContent : field.name;
            errorMessages.push(`${label.replace(':', '')}不能为空`);
            showError(field, '此字段为必填项');
        }
    });

    // 检查联系电话格式
    if (phoneField && phoneField.value && !/^1[3-9]\d{9}$/.test(phoneField.value.trim())) {
        isValid = false;
        errorMessages.push('联系电话格式不正确');
        showError(phoneField, '请输入有效的11位手机号码');
    }

    // 检查电子邮箱格式
    if (emailField && emailField.value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailField.value.trim())) {
        isValid = false;
        errorMessages.push('电子邮箱格式不正确');
        showError(emailField, '请输入有效的电子邮箱地址');
    }



    // 检查是否至少选择一个接受选项
    let acceptanceChecked = false;
    acceptanceOptions.forEach(option => {
        if (option.checked) acceptanceChecked = true;
    });
    if (!acceptanceChecked) {
        isValid = false;
        errorMessages.push('请至少选择一个可接受的工作条件');
        if (acceptanceValidation) {
            showError(acceptanceValidation, '请至少选择一项');
        }
    } else if (acceptanceValidation) {
        acceptanceValidation.value = 'valid';
    }

    // 显示汇总错误信息
    if (!isValid && errorMessages.length > 0) {
        const errorSummary = document.createElement('div');
        errorSummary.className = 'error-summary';
        errorSummary.innerHTML = `<strong>表单验证失败:</strong><ul><li>${errorMessages.join('</li><li>')}</li></ul>`;
        const formCard = form.closest('.form-card');
        if (formCard) {
            formCard.insertBefore(errorSummary, formCard.firstChild);
            // 滚动到错误信息
            errorSummary.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }

    return isValid;
}

// 显示错误信息
function showError(field, message) {
    const errorEl = document.createElement('div');
    errorEl.className = 'error-message';
    errorEl.textContent = message;
    field.classList.add('error');
    if (field.type === 'hidden') {
        // 对于隐藏字段，将错误信息显示在相关区域
        const parent = field.closest('.form-section');
        if (parent) {
            const title = parent.querySelector('h3');
            if (title) {
                title.parentNode.insertBefore(errorEl, title.nextSibling);
            } else {
                parent.appendChild(errorEl);
            }
        }
    } else if (field.nextElementSibling) {
        field.parentNode.insertBefore(errorEl, field.nextElementSibling);
    } else {
        field.parentNode.appendChild(errorEl);
    }
}


// 删除整个submitAccountingForm()函数及其事件绑定
function submitAccountingForm() {
    const formData = {
        formDate: document.querySelector('[name="formDate"]').value,
        name: document.querySelector('[name="name"]').value,
        gender: document.querySelector('[name="gender"]').value,
        // 收集所有字段...
        workExperience: [
            {
                time: document.querySelector('[name="workTime1"]').value,
                company: document.querySelector('[name="company1"]').value,
                position: document.querySelector('[name="position1"]').value,
                reason: document.querySelector('[name="reason1"]').value
            },
            // 收集其他工作经历...
        ],
        // 其他字段...
    };

    axios.post('/api/user/submit', formData)
        .then(response => {
            showToast('提交成功', 'success');
        })
        .catch(error => {
            showToast('提交失败，请重试', 'error');
        });
}

// 显示提示消息
function showToast(message, type = 'info') {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    
    // 添加到页面
    document.body.appendChild(toast);
    
    // 显示动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 100);
    
    // 3秒后自动移除
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            if (document.body.contains(toast)) {
                document.body.removeChild(toast);
            }
        }, 300);
    }, 3000);
}

// 在HTML中绑定提交事件
document.getElementById('accountingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    submitAccountingForm();
});